package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.article.domain.StrategyCommend;
import cn.wolfcode.luowowo.article.domain.TravelCommend;
import cn.wolfcode.luowowo.article.query.TravelQuery;
import cn.wolfcode.luowowo.article.service.IStrategyCommendService;
import cn.wolfcode.luowowo.article.service.ITravelCommendService;
import cn.wolfcode.luowowo.article.service.ITravelService;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.search.domain.DestinationTemplate;
import cn.wolfcode.luowowo.search.domain.StrategyTemplate;
import cn.wolfcode.luowowo.search.domain.TravelTemplate;
import cn.wolfcode.luowowo.search.domain.UserInfoTemplate;
import cn.wolfcode.luowowo.search.query.SearchQueryObject;
import cn.wolfcode.luowowo.search.query.StrategySearchQuery;
import cn.wolfcode.luowowo.search.service.*;
import cn.wolfcode.luowowo.search.vo.SearchResult;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
public class IndexController {

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Reference
    private ITravelCommendService travelCommendService;

    @Reference
    private IStrategyCommendService strategyCommendService;

    @Reference
    private ITravelService travelService;

    @Reference
    private IDestionationEsService destionationEsService;

    @Reference
    private IStrategyEsService strategyEsService;

    @Reference
    private ITravelEsService travelEsService;

    @Reference
    private IUserInfoEsService userInfoEsService;

    @Reference
    private ISearchService searchService;

    @RequestMapping("")
    public String index(Model model){
        //6. 用户再发请求会携带有key为token的cookie对象
        //注意 : 不止一个cookie, 所以需要遍历
//        Cookie[] cookies = request.getCookies();
//
//        //7. 遍历所有coolie, 找到name为token的cookie对象
//        //并通过这个cookie对象的value作为key查询Redis数据库的登录用户对象
//        String token = null;
//        if (cookies != null && cookies.length > 0){
//            for (Cookie c : cookies) {
//                if ("token".equals(c.getName())){
//                    token = c.getValue();
//                    c.setPath("/");
//                    c.setMaxAge(RedisKey.USER_LOGIN_TOKEN.getTime().intValue());
//                    response.addCookie(c);
//                    break;
//                }
//            }
//        }
//        String token = CookieUtil.getToken(request, response);
//        //注意 : 别忘记延长token在Redis的有效时间, 以及cookie在客户端的有效时间30分钟
//        //8. 在userInfoRedisService实现类中实现
//        UserInfo user = userInfoRedisService.getUserByToken(token);
//
//        //共享用户数据
//        request.getSession().setAttribute("userInfo", user);

        //tcs
        List<TravelCommend> top5 = travelCommendService.getTop5();
        model.addAttribute("tcs", top5);
        //sc
        StrategyCommend commend = strategyCommendService.getTop5().get(0);
        model.addAttribute("sc", commend);
        return "index/index";
    }

    @RequestMapping("/index/travelPage")
    public String travelPage(Model model, @ModelAttribute("qo") TravelQuery qo) {
        PageInfo pageInfo = travelService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        return "index/travelPageTpl";
    }

    @RequestMapping("/q")
    public String search(Model model, @ModelAttribute("qo")SearchQueryObject qo) {
        switch (qo.getType()) {
            case SearchQueryObject.SEARCH_TYPE_DEST:
                return this.searchDest(model, qo);
            case SearchQueryObject.SEARCH_TYPE_STRATEGY:
                return this.searchStrategy(model, qo);
            case SearchQueryObject.SEARCH_TYPE_TRAVEL:
                return this.searchTravel(model, qo);
            case SearchQueryObject.SEARCH_TYPE_USER:
                return this.searchUser(model, qo);
            default:
                return this.searchAll(model, qo);
        }
    }


    //全部
    private String searchAll(Model model, SearchQueryObject qo) {
        //用户
        Page<UserInfoTemplate> us = searchService.searchWithHighlight(UserInfoTemplate.INDEX_NAME, UserInfoTemplate.TYPE_NAME,
                UserInfoTemplate.class, qo, "nickName", "destName");
        model.addAttribute("page", us);

        //游记
        Page<TravelTemplate> ts = searchService.searchWithHighlight(TravelTemplate.INDEX_NAME, TravelTemplate.TYPE_NAME,
                TravelTemplate.class, qo, "title", "summary");
        model.addAttribute("page", ts);

        //攻略
        Page<StrategyTemplate> sts = searchService.searchWithHighlight(StrategyTemplate.INDEX_NAME, StrategyTemplate.TYPE_NAME,
                StrategyTemplate.class, qo, "title", "subTitle", "summary");
        model.addAttribute("page", sts);

        //目的地
        Page<DestinationTemplate> ds = searchService.searchWithHighlight(DestinationTemplate.INDEX_NAME, DestinationTemplate.TYPE_NAME,
                DestinationTemplate.class, qo, "name", "info");
        model.addAttribute("page", ds);

        SearchResult result = new SearchResult();
        result.setUsers(us.getContent());
        result.setTravels(ts.getContent());
        result.setStrategys(sts.getContent());
        result.setDests(ds.getContent());
        result.setTotal(sts.getTotalElements() + ts.getTotalElements()
                        + us.getTotalElements() + ds.getTotalElements());
        model.addAttribute("data", result);
        return "index/searchAll";
    }

    //用户搜索
    private String searchUser(Model model, SearchQueryObject qo) {
        Page<UserInfoTemplate> us = searchService.searchWithHighlight(UserInfoTemplate.INDEX_NAME, UserInfoTemplate.TYPE_NAME,
                UserInfoTemplate.class, qo, "nickName", "destName");
        model.addAttribute("page", us);
        return "index/searchUser";
    }

    //游记搜索
    private String searchTravel(Model model, SearchQueryObject qo) {
        Page<TravelTemplate> ts = searchService.searchWithHighlight(TravelTemplate.INDEX_NAME, TravelTemplate.TYPE_NAME,
                TravelTemplate.class, qo, "title", "summary");
        model.addAttribute("page", ts);
        return "index/searchTravel";
    }

    //攻略搜索
    private String searchStrategy(Model model, SearchQueryObject qo) {
        Page<StrategyTemplate> sts = searchService.searchWithHighlight(StrategyTemplate.INDEX_NAME, StrategyTemplate.TYPE_NAME,
                StrategyTemplate.class, qo, "title", "subTitle", "summary");
        model.addAttribute("page", sts);
        return "index/searchStrategy";
    }

    //目的地搜索
    //查询该目的地下所有的攻略, 游记, 用户
    private String searchDest(Model model, SearchQueryObject qo) {
        //1. 确定keyword是否是目的地
        DestinationTemplate dest = destionationEsService.findByName(qo.getKeyword());
        if (dest != null) {
            //2. 如果是查询该目的地下攻略, 游记, 用户
            List<StrategyTemplate> sts = strategyEsService.findByDestName(dest.getName());
            List<TravelTemplate> ts = travelEsService.findByDestName(dest.getName());
            List<UserInfoTemplate> us = userInfoEsService.findByDestName(dest.getName());
            //共享的是data数据
            SearchResult result = new SearchResult();
            result.setStrategys(sts);
            result.setTravels(ts);
            result.setUsers(us);
            long total = sts.size() + ts.size() + us.size();
            result.setTotal(total);
            model.addAttribute("data", result);
        }
        model.addAttribute("dest", dest);
        return "index/searchDest";
    }
}
